<template>
   <el-dialog
      v-model="open"
      :title="editId ? '编辑人员' : '添加人员'"
      width="60%"
      @close="onClose"
   >
      <el-form
         :model="form"
         :rules="rules"
         ref="formRef"
         label-width="100px"
      >
         <!-- 基本信息 -->
         <el-row :gutter="24">
            <el-col :span="12">
               <el-form-item
                  label="姓名："
                  prop="name"
               >
                  <el-input
                     v-model="form.name"
                     placeholder="请输入人员姓名"
                  />
               </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item
                  label="工号："
                  prop="num"
               >
                  <el-input
                     :disabled="editId"
                     v-model="form.num"
                     placeholder="工号为EMP+5位随机数"
                     style="width: calc(100% - 100px)"
                  />
                  <el-button
                     type="success"
                     style="margin-left: 10px"
                     @click="generateWorkNo"
                     :disabled="editId"
                     >分配工号</el-button
                  >
               </el-form-item>
            </el-col>
         </el-row>

         <el-row :gutter="24">
            <el-col :span="12">
               <el-form-item
                  label="性别："
                  prop="sex"
               >
                  <el-radio-group v-model="form.sex">
                     <el-radio :label="1">男</el-radio>
                     <el-radio :label="2">女</el-radio>
                  </el-radio-group>
               </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item
                  label="入职时间："
                  prop="job_date"
               >
                  <el-date-picker
                     v-model="form.job_date"
                     type="date"
                     placeholder="请选择入职时间"
                     style="width: 100%"
                     value-format="YYYY-MM-DD"
                  />
               </el-form-item>
            </el-col>
         </el-row>

         <!-- 联系方式 -->
         <el-row :gutter="24">
            <el-col :span="12">
               <el-form-item
                  label="手机号："
                  prop="mobile"
               >
                  <el-input
                     v-model="form.mobile"
                     placeholder="请输入手机号"
                     maxlength="11"
                  >
                     <template #prepend>
                        <span>中国+86</span>
                     </template>
                  </el-input>
               </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item
                  label="邮箱："
                  prop="email"
               >
                  <el-input
                     v-model="form.email"
                     placeholder="请输入邮箱"
                  />
               </el-form-item>
            </el-col>
         </el-row>

         <!-- 组织信息 -->
         <el-row :gutter="24">
            <el-col :span="12">
               <el-form-item
                  label="直属组织："
                  prop="org_id"
               >
                  <el-select
                     disabled
                     v-model="form.org_id"
                     placeholder="请选择直属组织"
                     style="width: 100%"
                     @change="handleOrgChange"
                  >
                     <el-option
                        v-for="item in departmentList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                     />
                  </el-select>
               </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item
                  label="职位："
                  prop="position_id"
               >
                  <el-select
                     v-model="form.position_id"
                     placeholder="请选择职位"
                     style="width: 100%"
                  >
                     <el-option
                        v-for="item in positionList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                     />
                  </el-select>
               </el-form-item>
            </el-col>
         </el-row>

         <!-- 状态信息 -->
         <el-row :gutter="24">
            <el-col :span="12">
               <el-form-item
                  label="员工状态："
                  prop="type"
               >
                  <el-radio-group v-model="form.type">
                     <el-radio :label="1">正式</el-radio>
                     <el-radio :label="2">兼职</el-radio>
                     <el-radio :label="3">试用</el-radio>
                  </el-radio-group>
               </el-form-item>
               <el-form-item
                  v-if="editId"
                  label="在职状态："
                  prop="job_status"
               >
                  <el-radio-group v-model="form.job_status">
                     <el-radio :label="1">在职</el-radio>
                     <el-radio :label="2">离职</el-radio>
                  </el-radio-group>
               </el-form-item>
               <el-form-item
                  label="是否主管："
                  prop="is_manager"
               >
                  <el-radio-group v-model="form.is_manager">
                     <el-radio :label="1">是</el-radio>
                     <el-radio :label="0">否</el-radio>
                  </el-radio-group>
               </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item
                  label="简历图片："
                  prop="intro_img"
               >
                  <el-upload
                     v-model:file-list="merchantPhotosImg"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload"
                     :action="publicDataStore.baseURL.split('/admin')[0] + '/api/upload'"
                     :limit="1"
                     accept=".jpg, .jpeg, .png"
                     list-type="picture-card"
                  >
                     <el-icon><Plus /></el-icon>
                  </el-upload>
               </el-form-item>
            </el-col>
         </el-row>

         <!-- 协助组织 -->
         <el-row>
            <el-col :span="24">
               <el-form-item
                  label="协助组织："
                  prop="org_ids"
               >
                  <div class="part-time-container">
                     <div
                        v-for="(item, index) in partTimeList"
                        :key="index"
                        class="part-time-item"
                     >
                        <el-select
                           v-model="item.org_id"
                           placeholder="请选择协助组织"
                           @change="(val) => handlePartTimeOrgChange(val, index)"
                        >
                           <el-option
                              v-for="dept in departmentList"
                              :key="dept.id"
                              :label="dept.name"
                              :value="dept.id"
                           />
                        </el-select>
                        <el-select
                           v-model="item.position_id"
                           placeholder="请选择职位"
                           @change="updatePartTimeData"
                        >
                           <el-option
                              v-for="pos in item.positionOptions || []"
                              :key="pos.id"
                              :label="pos.name"
                              :value="pos.id"
                           />
                        </el-select>
                        <el-button
                           type="danger"
                           class="delete-btn"
                           @click="removePartTime(index)"
                        >
                           删除
                        </el-button>
                     </div>
                  </div>
                  <el-button
                     type="primary"
                     link
                     @click="addPartTime"
                     class="add-org-btn"
                  >
                     <el-icon><Plus /></el-icon>
                     <span>添加协助组织</span>
                  </el-button>
               </el-form-item>
            </el-col>
         </el-row>
      </el-form>

      <template #footer>
         <div class="dialog-footer">
            <el-button @click="onClose">取 消</el-button>
            <el-button
               type="success"
               @click="onSubmit"
               >立即提交</el-button
            >
         </div>
      </template>
   </el-dialog>
</template>

<script setup>
   import { ref, reactive, watch } from "vue";
   import { Plus, Minus } from "@element-plus/icons-vue";
   import { ElMessage } from "element-plus";
   import { usePublicDataStore } from "@/stores/publicData"; // 导入 store
   import api from "@/api/index.js";
   const publicDataStore = usePublicDataStore();
   const open = ref(false);
   const formRef = ref(null);
   const merchantPhotosImg = ref([]);
   const editId = ref(""); // 编辑id
   // 兼职部门列表（用于UI展示）
   const partTimeList = ref([]);

   // 表单数据
   const form = ref({
      org_id: "", // 组织id
      org_ids: "[]", // 协助组织ID组。json格式:[1,2,3]
      position_id: "", // 职位ID
      position_ids: "[]", // 协助组织的职位ID组。Json格式:[3,4,5]
      name: "", // 员工姓名
      mobile: "", // 员工手机
      num: "", // 员工编号
      email: "", // 邮箱
      sex: 1, // 性别（0保密，1男，2女）
      type: 1, // 员工类型：1正式 2兼职 3试用
      intro_img: "", // 员工简历图片
      job_date: "", // 入职时间
      job_status: 1, // 在职状态：1在职；2离职
      is_manager: 0, // 是否主管：0否,1是
   });

   // 表单验证规则
   const rules = {
      name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      sex: [{ required: true, message: "请选择性别", trigger: "change" }],
      num: [{ required: true, message: "请输入工号", trigger: "blur" }],
      job_date: [{ required: true, message: "请选择入职时间", trigger: "change" }],
      mobile: [
         { required: true, message: "请输入手机号", trigger: "blur" },
         { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" },
      ],
      email: [
         { required: true, message: "请输入邮箱", trigger: "blur" },
         { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
      ],
      org_id: [{ required: true, message: "请选择直属组织", trigger: "change" }],
      position_id: [{ required: true, message: "请选择职位", trigger: "change" }],
      type: [{ required: true, message: "请选择员工类型", trigger: "change" }],
      job_status: [{ required: true, message: "请选择在职状态", trigger: "change" }],
      intro_img: [{ required: true, message: "请上传员工简历图片", trigger: "change" }],
   };

   // 部门列表
   const departmentList = ref([]);

   // 岗位列表
   const positionList = ref([]);
   const id = ref(0);
   // 组织详情
   const orgDetail = ref([]);
   const getOrgDetail = async () => {
      console.log("id", id.value);
      if (!id.value) {
         console.log("没有有效的组织ID");
         orgDetail.value = [];
         return;
      }
      try {
         const res = await api.authority.getOrgDetail({ id: id.value });
         if (res.code === 200 && res.data) {
            orgDetail.value = [{ id: res.data.id, name: res.data.name }];
         } else {
            console.error("获取组织详情失败:", res.msg);
            orgDetail.value = [];
         }
      } catch (error) {
         console.error("获取组织详情出错:", error);
         orgDetail.value = [];
      }
   };
   // 获取岗位列表
   const getPositionstList = async (value) => {
      id.value = value;
      try {
         const res = await api.authority.getPositionList({ org_id: value });
         if (res.code === 200) {
            return res.data.data.map((item) => ({
               id: item.id,
               name: item.position_name,
            }));
         }
         return [];
      } catch (error) {
         console.error("获取职位列表失败:", error);
         return [];
      }
   };

   // 获取部门列表
   const getDepartmentList = async () => {
      try {
         const res = await api.authority.getOrgList();
         if (res.code === 200) {
            departmentList.value = res.data.map((item) => ({
               id: item.id,
               name: item.name,
            }));
            departmentList.value.push(...orgDetail.value);
            console.log("departmentList", departmentList.value);
         }
      } catch (error) {
         console.error("获取部门列表失败:", error);
      }
   };

   // 处理直属组织变更
   const handleOrgChange = async (value) => {
      form.value.position_id = ""; // 清空职位选择
      if (value) {
         positionList.value = await getPositionstList(value);
      } else {
         positionList.value = [];
      }
   };

   // 处理协助组织变更
   const handlePartTimeOrgChange = async (value, index) => {
      if (value) {
         const positions = await getPositionstList(value);
         partTimeList.value[index].positionOptions = positions;
         partTimeList.value[index].position_id = ""; // 清空职位选择
      } else {
         partTimeList.value[index].positionOptions = [];
         partTimeList.value[index].position_id = "";
      }
      updatePartTimeData();
   };

   // 更新协助组织数据到表单
   const updatePartTimeData = () => {
      const orgIds = partTimeList.value.filter((item) => item.org_id).map((item) => item.org_id);

      const positionIds = partTimeList.value.filter((item) => item.position_id).map((item) => item.position_id);

      form.value.org_ids = JSON.stringify(orgIds);
      form.value.position_ids = JSON.stringify(positionIds);

      console.log("已更新协助组织数据", form.value.org_ids, form.value.position_ids);
   };

   // 添加协助组织
   const addPartTime = () => {
      partTimeList.value.push({
         org_id: "",
         position_id: "",
         positionOptions: [],
      });
   };

   // 移除协助组织
   const removePartTime = (index) => {
      partTimeList.value.splice(index, 1);
      updatePartTimeData(); // 移除时更新数据
   };

   // 生成工号
   const generateWorkNo = async () => {
      // 这里可以调用接口生成工号，或使用前端生成的临时工号
      const res = await api.authority.getRanNum({ type: "member" });
      if (res.code == 200) {
         form.value.num = res.data[0];
      }
   };

   // 头像上传相关方法
   const handleAvatarSuccess = (res) => {
      form.value.intro_img = res.data.url;
   };

   const beforeAvatarUpload = (file) => {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
         ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
         ElMessage.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
   };
   // 编辑组织人员
   const editPersonnel = async (data) => {
      try {
         formRef.value?.validate(async (valid) => {
            if (valid) {
               let params = {
                  id: editId.value,
                  ...form.value,
               };
               const res = await api.authority.editPosition(params);
               if (res.code === 200) {
                  ElMessage.success("编辑成功");
                  onClose();
                  // 触发父组件刷新列表
                  emit("refresh");
               } else {
                  ElMessage.error(res.msg || "编辑失败");
               }
            }
         });
      } catch (error) {
         console.error("编辑人员失败:", error);
         ElMessage.error("编辑失败，请稍后再试");
      }
   };
   // 打开弹窗
   const openDialog = async (data) => {
      open.value = true;

      // 如果有数据，设置id值为传入的org_id
      if (data && data.org_id) {
         id.value = data.org_id;
         // getUserDetail();
      }

      await getOrgDetail(); // 获取组织详情
      await getDepartmentList(); // 获取部门列表
      resetForm(); // 重置表单，避免上次的数据残留

      // 如果有数据，说明是编辑模式
      if (data) {
         editId.value = data.id;

         // 设置表单数据
         Object.keys(form.value).forEach((key) => {
            if (data[key] !== undefined) {
               if (key === "intro_img") {
                  if (data[key]) {
                     merchantPhotosImg.value = [{ url: data[key] }];
                     form.value.intro_img = data[key];
                  }
               } else {
                  form.value[key] = data[key];
               }
            }
         });

         // 处理协助组织数据
         if (data.org_ids && typeof data.org_ids === "string") {
            try {
               const orgIds = JSON.parse(data.org_ids);
               const positionIds = data.position_ids ? JSON.parse(data.position_ids) : [];

               // 设置协助组织列表
               if (orgIds.length > 0) {
                  for (let i = 0; i < orgIds.length; i++) {
                     const orgId = orgIds[i];
                     const posId = i < positionIds.length ? positionIds[i] : "";

                     // 获取该组织的职位列表
                     const positions = await getPositionstList(orgId);

                     partTimeList.value.push({
                        org_id: orgId,
                        position_id: posId,
                        positionOptions: positions,
                     });
                  }
               }
            } catch (e) {
               console.error("解析协助组织数据失败:", e);
            }
         }

         // 获取直属组织的职位列表
         if (form.value.org_id) {
            positionList.value = await getPositionstList(form.value.org_id);
         }
      }
   };

   // 重置表单
   const resetForm = () => {
      if (formRef.value) {
         formRef.value.resetFields();
      }

      // 保存当前的组织ID
      const currentOrgId = id.value;

      form.value = {
         org_id: currentOrgId || "", // 使用当前组织ID
         org_ids: "[]",
         position_id: "",
         position_ids: "[]",
         name: "",
         mobile: "",
         num: "",
         email: "",
         sex: null,
         type: null,
         intro_img: "",
         job_date: "",
         job_status: 1,
         is_manager: null,
      };

      partTimeList.value = [];
      merchantPhotosImg.value = [];
      positionList.value = [];

      // 如果有组织ID，获取该组织的职位列表
      if (currentOrgId) {
         handleOrgChange(currentOrgId);
      }
   };
   // 获取人员详情
   const getUserDetail = async () => {
      const res = await api.authority.getUserDetail({ id: id.value });
      if (res.code === 200) {
         form.value = res.data;
      }
   };
   // 关闭弹窗
   const onClose = () => {
      open.value = false;
      resetForm();
   };

   // 提交表单
   const onSubmit = () => {
      // 首先更新协助组织数据
      updatePartTimeData();

      if (editId.value) {
         editPersonnel();
      } else {
         formRef.value?.validate(async (valid) => {
            if (valid) {
               try {
                  const res = await api.authority.addPersonnel(form.value);
                  if (res.code === 200) {
                     ElMessage.success("添加成功");
                     onClose();
                     // 触发父组件刷新列表
                     emit("refresh");
                  } else {
                     ElMessage.error(res.msg || "添加失败");
                  }
               } catch (error) {
                  console.error("提交数据失败:", error);
                  ElMessage.error("添加失败，请稍后再试");
               }
            }
         });
      }
   };

   // 定义事件
   const emit = defineEmits(["refresh"]);

   defineExpose({
      openDialog,
   });
</script>

<style scoped>
   .part-time-container {
      display: flex;
      flex-direction: column;
      gap: 16px;
      margin-bottom: 16px;
      width: 100%;
   }

   .part-time-item {
      display: flex;
      align-items: center;
      gap: 16px;
      width: 100%;
   }

   .part-time-item .el-select {
      width: 40%;
   }

   .delete-btn {
      flex-shrink: 0;
      margin-left: auto;
   }

   .add-org-btn {
      margin-top: 8px;
   }

   .dialog-footer {
      display: flex;
      justify-content: center;
      gap: 16px;
      padding-top: 16px;
   }

   :deep(.el-form-item) {
      margin-bottom: 22px;
   }

   :deep(.el-input),
   :deep(.el-select) {
      width: 100%;
   }

   :deep(.el-upload--picture-card) {
      width: 148px;
      height: 148px;
      line-height: 148px;
   }
   ::v-deep .el-dialog {
      --el-dialog-padding-primary: 0px;
   }
   ::v-deep .el-dialog__header {
      padding: 10px 16px;
      border-bottom: 1px solid #f0f0f0;
      font-weight: bold;
   }
   ::v-deep .dialog-footer {
      padding: 10px 16px;
      border-top: 1px solid #f0f0f0;
   }
   ::v-deep .el-dialog__headerbtn .el-dialog__close {
      color: #000;
   }
   ::v-deep .el-dialog__body {
      padding: 10px 10px;
   }
   :deep(.el-form-item__label) {
      justify-content: flex-start;
   }
   :deep(.el-form-item) {
      flex-direction: column;
      margin-bottom: 7px;
   }
   :deep(.el-select__wrapper) {
      background: #fafcfb;
   }
   :deep(.el-badge__content.is-fixed) {
      color: #666;
      border-radius: 3px;
      padding: 4px;
   }
   :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
      width: 100%;
   }
   :deep(.el-button:hover) {
      color: #6860ff;
      background: #f4f5f7;
   }
   :deep(.el-input__wrapper.is-focus) {
      box-shadow: 0 0 0 1px #6860ff;
   }
   :deep(.el-select__wrapper.is-focused) {
      box-shadow: 0 0 0 1px #6860ff !important;
   }
</style>
